import React, { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import styles from './index.module.less'
import { Form, Input, Button, message } from 'antd'
import { UserOutlined, LockOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons'
import { LogoImg } from '@/assets/images/login'
import { getUserInfo, loginApi, getPublicKey } from '@/api/login'
import { useNavigate } from 'react-router'
import JSEncrypt from 'jsencrypt';
import { SUCCESS_CODE } from '@/config'

const LoginPage = () => {
  const [publicKey, setPublicKey] = useState<any>({})
  const navigate = useNavigate()
  const [form] = Form.useForm()
  useEffect(() => {
    const token = window.localStorage.getItem('token')
    if (token) {
        window.sessionStorage.setItem('token', token)
        navigate('/sys/')
    }

    // 获取公钥
    getPublicKey().then((res) => {
        res.status_code === SUCCESS_CODE ? (
            setPublicKey(res.data)
        ) : null
    })
}, [])

const initNodeRSA = (key: string, val: any) => {
  let encryptor = new JSEncrypt() // 新建JSEncrypt对象
  encryptor.setPublicKey(key) // 设置公钥
  // 对需要加密的数据进行加密
  return encryptor.encrypt(JSON.stringify(val)) || ''
}
const saveLogin = () => {
  form.validateFields().then((obj: any) => {
      loginApi({
          user: obj.user,
          password: initNodeRSA(publicKey, obj.password),
          type: 1
      }).then((res: any) => {
          if (res.status_code === SUCCESS_CODE) {
              console.log('登录成功')
              const { token_type, access_token } = res.data
              const token = `${token_type} ${access_token}`
              window.sessionStorage.setItem('token', token)
              window.localStorage.setItem('token', token)
              navigate('/sys/')
          }
      })
  })
}

  return (
    <div className={styles.login_layout}>
      <div className={styles.login_form_content}>
        <div className={styles.login_form_layout}>
          <div className={styles.login_form}>
            <p>
              <img src={LogoImg} />
              BIM
            </p>
            <Form autoComplete="off" name="normal_login" form={form} className="login-form" initialValues={{ remember: true }}>
              <Form.Item name="user" rules={[
                { required: true, message: '请输入账号!' },
                { pattern: /^[\da-zA-Z]+$/, message: '请输入正确的账号！' }
              ]}>
                <Input size='large' style={{ height: 46, marginBottom: 16 }} prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号" />
              </Form.Item>
              <Form.Item name="password" rules={[
                { required: true, message: '请输入密码!' },
                { max: 12, message: '请输入正确的密码！' },
                { pattern: /^[^\u4e00-\u9fa5]+$/, message: '请输入正确的密码！' }
              ]}>
                <Input.Password
                  size='large'
                  placeholder="密码"
                  style={{ height: 46 }}
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>
            </Form>
            <Button type="primary" onClick={saveLogin} htmlType="submit" className={styles.login_form_button}>
              登 录
            </Button>
          </div>
        </div>
      </div>
      <div className={styles.copyright_content}>
        <p>Copyright &copy; 广东保伦电子股份有限公司 粤ICP备16106620 V1.2.0</p>
      </div>
    </div>
  )
}

export default LoginPage
